<template>
    <div class="contest-index">
      <div class="contest-list">

<!--        比赛检索-->
        <div class="contest-search" style="margin-left: 40px;">
          <div>
            <el-input :placeholder="$t('contestMode.find')" v-model="params.key" class="input-with-select" clearable>

              <a href="javascript:void(0)" @click="getListData()" slot="append">
                <i class="el-icon-search"></i>
              </a>
            </el-input>
          </div>

<!--          筛选条件-->
          <div class="contest-search-select">
            <div v-if="isAdmin()">
              <div style="float: right;">
<!--                只看我的-->
                <el-checkbox  v-model="checkedCreated" @change="onlyMe">{{ $t('contestMode.onlyMe') }}</el-checkbox>

              </div>

            </div>
            <div v-if="isAdmin">
              <span>{{ $t('contestMode.public') }}</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
              <el-radio-group v-model="params.auth" @change="getListData()">
                <el-radio :label="''">{{ $t('contestMode.All') }}</el-radio>
                <el-radio :label="0">{{ $t('contestMode.public') }}&nbsp;&nbsp;&nbsp;&nbsp;</el-radio>
                <el-radio :label="1">{{ $t('contestMode.private') }}</el-radio>
              </el-radio-group>

            </div>
            <div>
              <span>{{ $t('contestMode.status.index') }}</span> &nbsp;&nbsp;&nbsp;&nbsp;
            <el-radio-group v-model="params.status" @change="getListData()">
              <el-radio :label="''">{{ $t('contestMode.All') }}</el-radio>
              <el-radio :label="0">{{ $t('contestMode.status.fir') }}</el-radio>
              <el-radio :label="1">{{ $t('contestMode.status.sec') }}</el-radio>
              <el-radio :label="2">{{ $t('contestMode.status.thi') }}</el-radio>
            </el-radio-group>
            </div>
            <div>
<!--              报名-->
              <span>{{ $t('contestMode.register.index') }}</span> &nbsp;&nbsp;&nbsp;&nbsp;
              <el-radio-group v-model="params.registered" @change="getListData()">
                <el-radio :label="''">{{ $t('contestMode.All') }}</el-radio>
                <el-radio :label="0">{{ $t('contestMode.register.fir') }}</el-radio>
                <el-radio :label="1">{{ $t('contestMode.register.sec') }}</el-radio>
              </el-radio-group>
            </div>
            <div v-if="isAdmin()">

              <span>
<!--                是否隐藏-->
                {{$t('contestMode.show.index')}}
              </span>&nbsp;&nbsp;&nbsp;&nbsp;
              <el-radio-group v-model="params.ishow" @change="getListData()">
                <el-radio :label="''">{{ $t('contestMode.All') }}</el-radio>
                <el-radio :label="0">{{ $t('contestMode.show.fir') }}</el-radio>
                <el-radio :label="1">{{ $t('contestMode.show.sec') }}</el-radio>
              </el-radio-group>

            </div>


          </div>
        </div>
        <!-- 创建比赛 -->
        <div style="height:32px" v-if="isAdmin()">
          <el-button size="small" type="info" style="background-color: #25bb9b;float: right;" @click="$router.push('/main/contest/save')" >
            {{ $t('contestMode.create') }}</el-button>
        </div>
        <!-- 比赛列表 -->
      <ul>
        <li v-for="(item,index) in listData" :key="item.id" class="contest-detail">

          <el-image
            style="width: 100px; height: 100px"
            :src="item.avatarId?'/api/user/download/'+item.avatarId:require('@/assets/logo.png')"
            fit="fit"></el-image>
            <div style="width:570px;margin-left: 10px;">
              <div>
                <!-- 比赛状态 -->
                <h3><router-link :to="'/main/contest/detail/'+item.id">{{ item.title }}</router-link></h3>
                <el-tag class="status" v-if="item.status==0"  size="mini" type="success" effect="dark">{{ $t('contestMode.status.fir') }}</el-tag>
                <el-tag class="status" v-if="item.status==1"  size="mini" type="danger" effect="dark">{{ $t('contestMode.status.sec') }}</el-tag>
                <el-tag class="status" v-if="item.status==2"  size="mini" type="info" effect="dark">{{ $t('contestMode.status.thi') }}</el-tag>


                <el-tag class="status" style="cursor:pointer" v-if="isAdmin()" size="mini" type="warning" effect="dark" @click="$router.push('/main/contest/save/?id='+item.id)">
                  {{ $t('update') }}</el-tag>
                <el-tag class="status" style="cursor:pointer" v-if="isAdmin()" size="mini" type="danger" effect="dark" @click="deleteById(item)">
                  {{ $t('delete') }}</el-tag>


              </div>
              <!-- 比赛信息 -->
              <div class="contest-text">
<!--                报名时间-->
                <div><i class="el-icon-time"></i> {{ $t('contestMode.registerTime') }}： {{item.registerBeginTime}} {{ $t('contestMode.to') }} {{ item.registerEndTime }}</div>
<!--                比赛时间-->
                <div><i class="fa fa-bell-o"></i> {{ $t('contestMode.time') }}： {{item.startTime}} {{ $t('contestMode.to') }} {{ item.endTime }}({{ $t('contestMode.timeLen') }}{{ getTimeDuration(item.startTime,item.endTime) }})</div>
<!--                主办方-->
                <div style="position: relative;">
                    <span><i class="fa fa-bookmark-o " style="width:12px;text-align: right;"></i> {{ $t('contestMode.author') }}： <router-link :to="'/main/user/detail/'+item.authorId" v-html="getUserName(item.authorId)"></router-link></span>
                  <router-link :to="'/main/contest/register?contestId='+item.id"><span style="position: absolute;left: 210px;"><i class="fa fa-users" style="color: grey;"></i> {{ $t('contestMode.joinPerson') }}：{{ item.registerPerson }}</span></router-link>

                </div>
              </div>

            </div>
            <div style="">
              <!-- 报名状态按钮 -->
              <div v-if="item.status!=2">
                <!-- 进入比赛按钮 -->
                <div>
                  <el-button type="success" v-if="item.registered&&item.status==1" round @click="init(item)">{{ $t('contestMode.join') }}</el-button>
                </div>
                <!-- 报名 -->
                <el-button type="success" v-if="!item.registered" round @click="saveRegister(item,index)">
                  {{ $t('contestMode.register.index') }}</el-button>
                <el-button type="info" round v-if="item.registered&&item.status==0" @click="cancelRegister(item,index)">
                  {{ $t('contestMode.register.sec') }}</el-button>

                <!-- 倒计时 -->
                <el-statistic v-if="item.status==0" @finish="setStatus(1,index)" :value="new Date(item.startTime).getTime()" time-indices title="" format="HH:mm:ss"  class="count-down">
                  <template slot="prefix"> {{ $t('contestMode.begin') }} </template>
                </el-statistic>
                <el-statistic v-if="item.status==1" @finish="setStatus(2,index)" :value="(new Date(item.endTime)).getTime()" time-indices title="" format="HH:mm:ss" class="count-down">
                  <template slot="prefix"> {{$t('contestMode.end')  }} </template>
                </el-statistic>
              </div>
              <!-- 比赛已结束 -->
              <div v-if="item.status==2">
                <el-button type="info" round  @click="init(item)">{{$t('contestMode.returnJoin') }}</el-button>
              </div>

            </div>


        </li>
      </ul>
        <!--分页-->
        <div class="page">
          <el-pagination
              background
              layout="prev, pager, next"
              :total="total"
              :page-size="params.size"
              :page-sizes="[10,20,30,50,100]"
              @current-change="chg"
              @size-change="chgsize"
          >
          </el-pagination>
        </div>
      </div>
<!--      比赛rating积分排行榜-->
      <div class="contest-rank">
        <h3 style="margin: 10px;"><span style="display: inline-block;background-color: #ff6547;height: 7px;width: 7px;margin-right: 5px;margin-bottom: 3px;">  </span>Rating {{ $t('contestMode.rank.index') }}</h3>
        <hr/>
        <div v-for="(item,index) in ratingList" :key="item.id" style="margin-top: 10px;margin-bottom: 5px;">
          <span :style="'padding-left: 10px;'+(index<3?'color: #f0d29a;':'')">{{index+1}}</span>
          <span :style="'padding-left: 10px;'+ (index<5?'color:#ff0000;':'color:#ffd692;')"> {{item.username}} </span>
          <span :style="'float: right;padding-right: 10px;' + (index<5?'color:red;':'color:grey;')"> {{item.rating}} </span>
        </div>
        <el-button v-if="flagRating" type="info" plain style="border-radius: 0;width: 100%;" @click="flagRating = false;getRatingTable(1,50)">
<!--          查看更多-->
          {{ $t('contestMode.rank.more') }}</el-button>
        <el-button v-if="!flagRating" type="info" plain style="border-radius: 0;width: 100%;" @click="flagRating = true;getRatingTable(1,10)">
<!--          最多展示前五十名-->
          {{$t('contestMode.rank.end')}}
        </el-button>
      </div>

    </div>
  </template>

  <script lang="ts">
import * as contestApi from '@/api/contest'
import {getEasyUserById,getRating} from '@/api/admin'
import { isAdmin , loginUser ,isLogin} from '@/utils/auth';
  export default {
    name: 'contestIndex',
    data() {
      return {
        listData: [],
        total:0,
        flagRating:true,
        params:{
          key:"",
        },
        userNames:{},
        checkedCreated:false,
        ratingList:[],//用户的rating排名
        // registered:{},  //报名信息
      };
    },
    methods: {
      //每页记录数发生改变时
      chgsize(pgsize) {
        //更改每页记录数
        this.params.size = pgsize;
        //从每一页开始查询
        this.params.page = 1;
        //重新查询
        this.getListData(this.params);
      },
      //当页数发生变化时执行
      chg(curpage) {
        //更新查询的页数
        this.params.page = curpage;
        //重新查询
        this.getListData(this.params);
      },
      // 只看我创建的比赛
      onlyMe(){
        if(this.checkedCreated){
          this.params.userId = loginUser().id;
        }else{
          this.params.userId = '';
        }
        this.getListData();
      },
      //进入比赛
      init(data){
        this.$router.push({path:"/main/contest/detail/"+data.id,params:{"activeName":"question","id":data.id},name:"contestDetail"})
      },
      //删除比赛
      deleteById(item){
        this.$confirm(this.$t('problemMode.case.deleteWarnBefore')+item.title+this.$t('problemMode.case.deleteWarnAfter'), this.$t('prompt'), {
          confirmButtonText: this.$t('save'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }).then(() => {
          contestApi.deleteById({"id":item.id}).then(res=>{
            if(res.data.success){
              this.$message({
                type: 'success',
                message: this.$t('delete')+this.$t('success')
              });
              this.getListData();
            }
          })
        })
      },
      getListData(){
        contestApi.getListData(this.params).then(async res=>{
          if(res.data.data){
          var tables = res.data.data.dataList;
          //获取用户名字
          for(var i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)
            if(!this.userNames[tables[i].authorId]){
              await getEasyUserById({"id":tables[i].authorId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data.username;
                }else{
                  this.userNames[tables[i].authorId] =  '<span style="color:grey;" disabled>'+this.$t('UnKnownUser')+'</span>';
                }
              });
            }
          }
          //获取报名信息
          for(i = 0;i<tables.length;i++){
            await contestApi.contesResgister({"id":tables[i].id}).then(res3=>{
              if(res3.data.data){
                tables[i].registered = true;
              }
            })
          }
          this.listData = tables;
          // console.info()
          this.total = res.data.data.total;
          }
        })
      },
      // 获取时间差
      getTimeDuration(time1,time2){
        var x = new Date(time2).getTime()-new Date(time1).getTime(); //毫秒
        var min = Math.floor(x/1000/60);  //分钟
        var hour = Math.floor(min/60);
        var res = "";
        if(hour!=0)res+=hour + '小时';
        if(min%60!=0)res += (min%60)+"分钟";
        return res;
      },
          //根据信息userId获取用户名
      getUserName(id){
        return this.userNames[id];
      },
      //报名
      saveRegister(data,index){
        // var password = "";
        if(data.auth==1){  //需要密码
          this.$prompt(this.$t('contestMode.need')+this.$t('contestMode.password'), this.$t('prompt'), {
          confirmButtonText: this.$t('save'),
          cancelButtonText: this.$t('cancel'),
        }).then(({ value }) => {  //需要邀请码
          contestApi.saveRegister({"contestId":data.id,"password":value}).then(res=>{
            if(res.data.success){
              // 报名成功
              this.$message({"type":"success",message:this.$t('contestMode.register.index')+this.$t('success')});
              this.listData[index].registered = true;
              this.listData[index].registerPerson++;
              this.$set(this.listData,index,this.listData[index])
              // data.registered = true;
            }
          })
        });

        }else{ //不需要邀请码
          contestApi.saveRegister({"contestId":data.id}).then(res=>{
            if(res.data.success){
              // 报名成功
              this.$message({"type":"success",message:this.$t('contestMode.register.index')+this.$t('success')});
              this.listData[index].registered = true;
              this.listData[index].registerPerson++;
              this.$set(this.listData,index,this.listData[index])
              // data.registered = true;
            }
          })
        }

      },
      //取消报名
      cancelRegister(data,index){
        contestApi.cancelRegister({"id":data.id}).then(res=>{
          if(res.data.success){
            // 取消报名成功
            this.$message({type:"info",message:this.$t('cancel')+this.$t('contestMode.register.index')+this.$t('success')});
            this.listData[index].registered = false;
            this.listData[index].registerPerson--;
            this.$set(this.listData,index,this.listData[index])
          }
        });
      },
      //设置比赛的状态值
      setStatus(status,index){
        this.listData[index].status = status;
        this.$set(this.listData,index,this.listData[index])
      },
      //判断是否为管理员
      isAdmin(){
      // console.info(isAdmin())
      return isAdmin();
      },
      getRatingTable(page,size){
        getRating({"page":page,"size":size}).then(res=>{
          if(res.data.success){
            this.ratingList = res.data.data.dataList;
          }
        })
      },
    },
    created(){
      this.getListData();
      //获取rating积分榜
      this.getRatingTable(1,10);
    },


  }
</script>

  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style scoped>
  .contest-index{
    text-align: left;
    vertical-align: top;
  }
  .contest-index .contest-rank{
    width: 300px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    background-color: #ffffff;
    display: inline-block;
    margin-left: 100px;
    vertical-align: top;
    margin-top: 10px;
  }
  .contest-index .contest-list{
  width: 870px;
    display: inline-block;
    /*margin-left: -30%;*/
    /*position: absolute;*/
    margin-left: 5%;
    vertical-align: top;

  }
  .contest-index .contest-list > ul{
    list-style: none;
    margin-left: 0px;
    padding-top: 0px;
    margin-top: 0px;
    vertical-align: top;

  }
  .contest-index .contest-list .contest-detail{
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    /* list-style: none; */
    margin-top: 10px;
    padding: 15px;
    background-color: #ffffff;
    text-align: left;
    border-radius: 10px;
    vertical-align: top;
    overflow: hidden;
  }
  .contest-index .contest-list .contest-detail > div{
    float: left;
    /* margin-left: 5px; */
  }
  .contest-index .contest-list .contest-detail > div .status{
    /* font-size: 65%; */
    /* margin-top: -5px; */
    margin-left: 5px;
    /* border-radius: 0px; */
  }
  .contest-index .contest-list .contest-detail h3{
    display: inline-block;
    margin-top: 2px;
    position: relative;
    margin-bottom: 0px;
    font-weight: 400;
    font-size: 18px;

    /* float: left; */
  }
  .contest-index .contest-list .contest-detail .contest-text{
    font-size: 14px;
    margin-top: 7px;
    /* float: left; */
  }

  .contest-index .contest-list .contest-detail .contest-text > div{
  margin-top: 5px;
  margin-bottom: 5px;
  /* float: left; */
}
  .contest-index .contest-list .page{
    text-align: center;
  }
  .contest-index .contest-list .contest-search{
  /* list-style: none; */
  margin-top: 10px;
  /*padding: 15px;*/
  /*background-color: #ffffff;*/
  text-align: left;
  vertical-align: top;
  overflow: hidden;
}
.contest-index .contest-list .contest-search .contest-search-select{
  background-color: #f4f4f4;
  margin-top: 10px;
  padding: 15px;
}
.contest-index .contest-list .contest-search .contest-search-select > div{
  margin-top: 12px;
}
.contest-index .contest-list .contest-search .contest-search-select > div span{
  font-size: 88%;
  font-weight: 700;
}
</style>
<style>
.contest-index .contest-list .contest-detail .count-down .number{
  font-size: 14px;color: grey;
}

.contest-index .contest-list .contest-detail  .count-down{
  font-size: 14px;color: grey;
  margin-top: 5px;
}
.contest-index .contest-list .contest-detail  button{
  width:105px
}
.contest-index .contest-list .contest-search .el-input-group__append{
  background-color: #ffffff;

}
</style>
